package com.mes.cotask.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.mes.cotask.dao.iface.ICotaskDao;
import com.mes.cotask.domain.Cotask;
import com.mes.task.dao.PartTaskDao;
import com.mes.task.domain.OperationTask;
import com.mes.task.domain.PartTask;
import com.mes.common.dao.BasicDao;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;

@Repository
public class CotaskDao extends BasicDao<Cotask> implements ICotaskDao{
	private static final Log log = LogFactory.getLog(CotaskDao.class);

	@Autowired
	PartTaskDao partTaskDao;
	
	@Override
	public Cotask findByTaskUid(String taskUid) throws Exception {
		List<?> cotaskList = this.findByProperty("taskUid", "%" + taskUid + "%");
		if( cotaskList.size() != 0 ){
			return (Cotask) cotaskList.get(0);
		}else {
			return null;	
		}
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<OperationTask> getHistoryTask(OperationTask operationTask) throws Exception{
		if (this.getSession() == null) {
			throw new Exception("会话失效，请重新登录!");
		}
		
		Criteria criteria = this.getSession().createCriteria(OperationTask.class);
		Criterion ctnOpuid = Expression.eq("operationUid", operationTask.getOperationUid());
		Criterion ctnState = Expression.ge("taskState", 209);
		criteria.add(ctnOpuid);
		criteria.add(ctnState);
		criteria.addOrder(Order.asc("operationId"));
		
		return criteria.list();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Cotask> findHistoryCotasksByPrevMonth(String deptId) throws Exception{
		List<Cotask> historyCotasks = null;
		//deptId = deptId.length() > 4 ? deptId.substring(0,4) : deptId;
		int currentMonth =  Calendar.getInstance().get(Calendar.MONTH);
		String queryString = "from com.mes.cotask.domain.Cotask as cotask where (extract(month from cotask.scheduleStart)-1)=" + currentMonth + " and cotask.masterShop like '"+ deptId +"' || '%' order by cotask.scheduleStart";
		historyCotasks = this.query(queryString);
		
		return historyCotasks;
	}
	
	@Override
	public int getPriority(Cotask cotask) throws Exception{
		PartTask part = (PartTask) partTaskDao.getById(cotask.getPartTaskUid());
		Date nowDate = new Date();
		Calendar now = Calendar.getInstance();
		long lagDayCur = now.getMaximum(Calendar.DAY_OF_MONTH) - now.get(Calendar.DAY_OF_MONTH);
		now.set(Calendar.MONTH, now.get(Calendar.MONTH)+1);
		long lagDayNex = lagDayCur + now.getMaximum(Calendar.DAY_OF_MONTH);//第一个月
		
		if (part.getLateFinish() == null) {
			return 0;
		}else if (part.getLateFinish().getTime() > lagDayNex*24*60*60*1000 + nowDate.getTime()) {//两个月以后
			return 0;
		}else if (part.getLateFinish().getTime() > lagDayCur*24*60*60*1000 + nowDate.getTime()) {//下个月的任务
			if (part.getIsCritical() == null || part.getIsCritical().compareTo(0) == 0) {
				return 1;//非关键
			}else {
				return 2;
			}
		}else {//本月任务
			if (part.getIsCritical() == null || part.getIsCritical().compareTo(0) == 0) {
				return 3;//非关键
			}else if (part.getIsCritical().compareTo(1) == 0) {
				return 4;//关键
			}else {
				return 5;//最关键
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Cotask getFirstUncompleteCotask(String partNumber,String batchNum) throws Exception{
		try {
			
			Criteria criteria  = this.getSession().createCriteria(Cotask.class);
			Criterion ctnPart  = Expression.eq("partNumber", partNumber);
			Criterion ctnBatch = Expression.eq("batchNum", batchNum);
			//修改成只有没有彻底入库都能查到
			Criterion ctnState = Expression.lt("cotaskState",  Cotask.COTASK_STATE_DELIVERIED);
			
			criteria.add(ctnPart);
			criteria.add(ctnBatch);
			criteria.add(ctnState);
			criteria.addOrder(Order.asc("createTime"));
			
			List<Cotask> allCotasks = criteria.list();
			
			return allCotasks == null || allCotasks.isEmpty() ? null : allCotasks.get(0);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
		return null;
	}
	
	/**
	 * 通过给定的taskUid返回一个Cotask对象
	 * @param taskUid
	 * @return Cotask
	 * @throws Exception
	 */
	public Cotask getCotaskByTaskUid(String taskUid) throws Exception{
		List<Cotask> all = this.findByProperty("taskUid", "%" + taskUid + "%");
		if (all.isEmpty()) {
			return null;
		}else {
			if (all.size() > 1) {
				return null;
			}
			return all.get(0);
		}
	}
	
	
	
}
